package myJs.user.soft

import myJs.Implicits._
import myJs.Utils._
import scala.scalajs.js.Dynamic.{global=>g}
import myJs.myPkg.LayerOptions
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.tool.Pojo._
import myJs.tool.Tool
import myJs.tool.Tool._
import myJs.user.soft.fileSelect._
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._

import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("MetMicCor")
object MetMicCor {

  val formId = "form"
  val fileModalId = "fileModal"
  val tableId = "table"
  val timeFieldNames = List[String]()

  val curSoft = Tool.kindSoftFMap(MetMicCorSoft.nameStr)

  @JSExport("init")
  def init = {
    FileModal.init
    registerEvent

    bootStrapValidator
    $("#form").bv.revalidateField("missionName")
    Tool.refreshCalculateConfig { rs =>
    }
    VideoCp.Props(soft=MetMicCorSoft).render.renderIntoDOM(document.querySelector("#videoRoot"))

  }

  def registerEvent = {
    $(document.body).on("click", ".myRun", "", (y: Element) => {
      myRun
    })
    $(document.body).on("change", ".myCov", "", (y: Element, e: Event) => {
      covChange(y)
    })
    $(document.body).on("click", ".myFileSelect", "", (y: Element) => {
      val name = $(y).dataInputName
      val metDataFileName = Tool.getInputByName("file").myVal
      val lis = $(y).dataValue.split(";")
      $(".myFileSelect").removeClass("myCurrent")
      $(y).addClass("myCurrent")
      FileModal.fileSelectShow(lis)
    })

    $(document.body).on("click", ".myFileSelectButton", "", (y: Element) => {
      val folder = $(y).dataFolder
      val fileName = $(y).dataFileName
      Tool.fileSelect(folder, fileName)
    })
  }

  def covChange(y: Element) = {
    val showJq = $("#covFile")
    if ($(y).isChecked) {
      showJq.show()
    } else {
      showJq.hide()
    }
    $("#form").bv.revalidateField("covFile")
  }

  @JSExport("myRun")
  def myRun = {
    val bv = $("#form").bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", messages("running"),
          span(id := "progress", "。。。")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.title(zhInfo).closeBtn(0).skin("layui-layer-molv").btn(js.Array())
      val index = layer.alert(element, layerOptions)
      val url = g.jsRoutes.controllers.SoftController.analysis().url.toString
      val formData = $(s"#form").serialize()
      Ajax.post(url = s"${url}", data = s"${formData}&kind=${curSoft.nameStr}",
        headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        layer.close(index)
        val valid = rs("valid").toB
        if (valid) {
          window.location.href = g.jsRoutes.controllers.MissionController.missionManageBefore().url.toString
        } else {
          g.swal("Error", rs.myGet("message"), "error")
        }
      }
    }
  }

  def getId = {
    g.id.toString
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.MissionController.missionNameCheck().url.toString
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "missionName" ->{
          val info=messages("taskName")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("exist")}",
                "url" -> url,
                "type" -> "POST",
                "delay" -> 1000,
                "data" -> js.Dictionary(
                  "kind" -> curSoft.nameStr
                )
              ),
            )
          )
        } ,
        "file" -> {
          val info = messages("dataMatrix")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("notExist")}",
                "url" -> Tool.fileNameCheckUrl,
                "type" -> "POST",
                "delay" -> 1000,
                "name" -> "fileName",
              ),
            )
          )
        },
        "micFile" -> {
          val info = messages("dataMatrixOfMicrobiota")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("notExist")}",
                "url" -> Tool.fileNameCheckUrl,
                "type" -> "POST",
                "delay" -> 1000,
                "name" -> "fileName",
              ),
            )
          )
        },
        "covFile" -> {
          val info = messages("dataMatrixOfCovariates")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${messages("notExist")}",
                "url" -> Tool.fileNameCheckUrl,
                "type" -> "POST",
                "delay" -> 1000,
                "name" -> "fileName",
              ),
            )
          )
        },
        "coe" -> {
          val info = messages("correlationCutoff")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${messages("numeric")}",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 1,
                "message" ->  s"${messages("between", 0, 1)}",
              ),
            )
          )
        },
        "p" -> {
          val info = messages("pValueCutoff")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${messages("null")}"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${messages("numeric")}",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 1,
                "message" ->  s"${messages("between", 0, 1)}",
              ),
            )
          )
        },
        "r" -> {
          val info = messages("coefficientCutoff")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${messages("numeric")}",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 1,
                "message" ->  s"${messages("between", 0, 1)}",
              ),
            )
          )
        },
        "alpha" -> {
          val info = messages("pCutoff")
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" ->s"${messages("null")}"
              ),
              "numeric" -> js.Dictionary(
                "message" -> s"${messages("numeric")}",
              ),
              "between" -> js.Dictionary(
                "min" -> 0,
                "max" -> 1,
                "message" ->  s"${messages("between", 0, 1)}",
              ),
            )
          )
        },
      )
    )
    $(s"#form").bootstrapValidator(dict)
  }


}
